package com.hst.capacity.domain.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import com.hst.capacity.domain.model.entity.auth.TokenEntity;
import com.hst.capacity.domain.model.response.auth.LoginUser;
import com.hst.capacity.domain.service.TokenService;
import com.hst.capacity.domain.service.UserService;
import com.hst.capacity.infra.persistence.jpa.TokenRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;

@Slf4j
@Service
public class TokenServiceImpl implements TokenService {

    @Value("${capacity.token.expires}")
    private long expires;

    @Autowired
    private TokenRepository tokenRepository;

    @Autowired
    private UserService userService;

    @Override
    public TokenEntity createAccessToken(String userId) {
        TokenEntity tokenEntity = new TokenEntity().setUserId(userId)
                .setAccessToken(IdUtil.fastSimpleUUID())
                .setExpires(Instant.now().getEpochSecond() + expires);
        //写入数据库
        tokenRepository.save(tokenEntity);

        return tokenEntity;
    }

    @Override
    public TokenEntity getAccessToken(String accessToken) {
        return tokenRepository.findByAccessToken(accessToken);
    }

    /**
     * 访问令牌有效性校验
     *
     * @param accessToken 访问令牌
     */
    @Override
    public boolean verifyAccessToken(String accessToken) {
        TokenEntity tokenEntity = getAccessToken(accessToken);
        if (ObjUtil.isNotNull(tokenEntity)) {
            if (tokenEntity.getExpires() > Instant.now().getEpochSecond())
                return true;
        }
        return false;
    }

    @Override
    public void destroyAccessToken(String userId) {
        tokenRepository.deleteById(userId);
    }

    /**
     * 按访问令牌，列表查询用户角色
     *
     * @param accessToken 访问令牌
     */
    @Override
    public LoginUser getLoginUser(String accessToken) {
        TokenEntity tokenEntity = getAccessToken(accessToken);
        if (ObjUtil.isNotNull(tokenEntity)) {
            return new LoginUser(userService.getUser(tokenEntity.getUserId()), userService.getAuthorities(tokenEntity.getUserId()));
        }
        return null;
    }

}
